'use strict'

import React, { Component } from 'react'

import { StyleSheet, View, ScrollView, TouchableOpacity, Text, Platform, Image, ListView, Alert,InteractionManager } from 'react-native'

import BasePage from '../common/BasePage'
import Constants from '../../common/Constants'
import SizeUtils from '../../common/SizeUtils'
import TImage from '../../components/TImage'
import Config from '../../config'
import ToastUtils from '../../common/ToastUtils'
import NoticeIcon from '../user/NoticeIcon'
import CommonViewPagerMultiShow from '../common/CommonViewPagerMultiShow'
import CommonAvatarView from '../common/CommonAvatarView'
import CommonStyles from '../../common/CommonStyles'
import QZ_RequestQuanziListAction from '../../actions/quanzi/QZ_RequestQuanziListAction'
import QuanziRequestFindAction from '../../actions/quanzi/QuanziRequestFindAction'
import QuanziSendShoucangQuanziAction from '../../actions/quanzi/QuanziSendShoucangQuanziAction1'
import CommonCheckUserTypeAction from '../../actions/common/CommonCheckUserTypeAction'

var ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })

class QuanziFindPage extends BasePage {
  constructor(props) {
    super(props)
    this._viewPager = null
    this.state.listData = []
  }
  componentWillUpdate(nextProps, nextState) {
    if (nextState.isResponeUpdate == true) {
      nextState.isResponeUpdate = false
      if (nextState.data && nextState.data instanceof Array) {
        nextState.listData = nextState.data
      } else {
        nextState.listData = []
      }
      if (nextState.isChage) {
        nextState.isChage = false
        ToastUtils.show(nextState.tdata.is_favorited === 1 ? '成功退出圈子' : '成功加入圈子')
        this._requestData()
      }
    }
  }
  componentDidMount() {
    InteractionManager.runAfterInteractions(()=>{
      this.setState({
        componentReady: true,
      })
      this._requestData()
    })
  }
  _dealEnterPage() {
    setTimeout(() => {
      this._requestData()
    }, 2000)
  }

  _renderViewPage() {
    return <CommonViewPagerMultiShow ref={ref => (this._viewPager = ref)} type={Constants.SLIDER_TYPE.INDEX} />
  }
  _requestData() {
    this._viewPager && this._viewPager.doRefresh()
    new QZ_RequestQuanziListAction().call(this, { page: 1 })
    new QuanziRequestFindAction().call(this, { page: 1 })
  }
  getObj() {
    var obj = []
    if (this.state.qunData) {
      obj.push({ hot: this.state.qunData.hot })
      for (var i = 0; i < this.state.qunData.index.length; i++) {
        const item = this.state.qunData.index[i]
        const keyt = item.index.toUpperCase()
        var o = {}
        o[keyt] = item.boards
        obj.push(o)
      }
    }
    return obj
  }
  render() {
    if (this.state.componentReady === false) {
      return<View/>
    }
    return (
      <View style={this.props.style}>
        {this._renderTitleView()}
        <ScrollView style={{ flex: 1 }} ref={ref => (this._scrollView = ref)}>
          {this._renderViewPage()}
          <View style={{ flexDirection: 'column' }}>
            {this._renderHeader('我的圈子', 'my')}
            {this.state.listData.length > 0 ? (
              <ListView
                horizontal={true}
                enableEmptySections={true}
                showsHorizontalScrollIndicator={false}
                dataSource={ds.cloneWithRows(this.state.listData)}
                renderRow={this._renderRow.bind(this)}
              />
            ) : (
              <View
                style={{
                  height: SizeUtils.translateDesignHeightToCode(180),
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                <Text>{'暂无关注'}</Text>
              </View>
            )}
          </View>
          <View style={{ backgroundColor: '#f2f2f2', height: 10 }} />
          {this._renderHeader('热门圈子', 'hot')}
          <View
            style={{
              width: SizeUtils.getWindowSize().width
            }}
          >
            {this.getObj().map((data, index) => {
              return this._renderHotView(data, index)
            })}
          </View>
        </ScrollView>
        {this.getObj().length > 0 ? (
          <View
            style={{
              position: 'absolute',
              right: 4,
              top: 200,
              width: 20,
              paddingTop: 6,
              paddingBottom: 6,
              backgroundColor: '#00000066',
              borderRadius: 10
            }}
          >
            {this.getObj().map((data, index) => {
              var arr = Object.keys(data)
              var keyval = arr[0] || ''
              return (
                <TouchableOpacity
                  style={{ height: 20 }}
                  key={'sk' + keyval}
                  onPress={() => {
                    this._onPressSectionItem(keyval)
                  }}
                >
                  <Text
                    numberOfLines={1}
                    style={[
                      CommonStyles.primaryText,
                      {
                        textAlign: 'center',
                        fontWeight: 'bold',
                        color: '#fff',
                        fontSize: SizeUtils.translateFontSizeToCode(24)
                      }
                    ]}
                  >
                    {keyval == 'hot' ? '热' : keyval}
                  </Text>
                </TouchableOpacity>
              )
            })}
          </View>
        ) : null}
      </View>
    )
  }
  _onPressSectionItem(numval) {
    this.refs[numval] &&
      this.refs[numval].measure((ox, oy, width, height, px, py) => {
        this._scrollView &&
          this._scrollView.scrollTo({
            x: 0,
            y: Math.max(0, oy + SizeUtils.translateDesignWidthToCode(440)),
            animated: true
          })
      })
  }
  _renderRow(data, index) {
    return (
      <TouchableOpacity
        onPress={() => {
          this._onPressItem(data)
        }}
        style={{
          flex: 1,
          overflow: 'hidden',
          alignItems: 'center',
          justifyContent: 'center',
          width: SizeUtils.translateDesignWidthToCode(140),
          height: SizeUtils.translateDesignHeightToCode(180),
          marginTop: SizeUtils.translateDesignHeightToCode(20),
          marginBottom: SizeUtils.translateDesignHeightToCode(20),
          marginLeft: SizeUtils.translateDesignWidthToCode(20),
          borderWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee',
          borderRadius: 4
        }}
      >
        <CommonAvatarView avatarUri={this._getImageSource(data)} size={110} />
        <Text
          numberOfLines={1}
          style={[
            CommonStyles.primaryText,
            {
              marginTop: SizeUtils.translateDesignHeightToCode(10),
              color: '#000',
              fontSize: SizeUtils.translateFontSizeToCode(24)
            }
          ]}
        >
          {data.title}
        </Text>
      </TouchableOpacity>
    )
  }
  _renderHotView(data, index) {
    var arr = Object.keys(data)
    var keyval = arr[0] || ''
    var array = data[keyval] || []
    // var array = this.state.listData||[];
    return (
      <View
        key={'hotbox' + index}
        ref={keyval}
        style={{
          width: SizeUtils.getWindowSize().width,
          paddingTop: SizeUtils.translateDesignHeightToCode(20),
          paddingBottom: SizeUtils.translateDesignHeightToCode(20),
          flexDirection: 'row',
          flexWrap: 'wrap'
        }}
      >
        <Text
          style={{
            height: SizeUtils.translateDesignHeightToCode(keyval !== 'hot' ? 30 : 0),
            lineHeight: SizeUtils.translateDesignHeightToCode(30),
            paddingLeft: SizeUtils.translateDesignWidthToCode(26),
            width: SizeUtils.getWindowSize().width
          }}
        >
          {keyval !== 'hot' ? keyval : ''}
        </Text>
        {array.map((data, index) => {
          return this._renderHotConentView(data, index)
        })}
      </View>
    )
  }
  _renderHotConentView(data, index) {
    return (
      <TouchableOpacity
        key={'hotc' + index}
        onPress={() => {
          this._onPressItem(data)
        }}
        style={{
          overflow: 'hidden',
          width: (SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(60)) / 2,
          height: SizeUtils.translateDesignHeightToCode(180),
          marginTop: SizeUtils.translateDesignHeightToCode(index > 1 ? 20 : 0),
          paddingLeft: SizeUtils.translateDesignWidthToCode(10),
          paddingRight: SizeUtils.translateDesignWidthToCode(10),
          marginLeft: SizeUtils.translateDesignWidthToCode(20),
          borderWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee',
          borderRadius: 2
        }}
      >
        <View
          style={{
            flex: 1,
            flexDirection: 'row',
            alignItems: 'center'
          }}
        >
          <CommonAvatarView avatarUri={this._getImageSource(data)} size={110} />
          <View
            style={{
              height: SizeUtils.translateDesignHeightToCode(110),
              marginLeft: SizeUtils.translateDesignWidthToCode(10),
              flex: 1
            }}
          >
            <Text
              numberOfLines={1}
              style={[
                CommonStyles.primaryText,
                {
                  marginTop: SizeUtils.translateDesignHeightToCode(10),
                  color: '#000',
                  fontSize: SizeUtils.translateFontSizeToCode(24)
                }
              ]}
            >
              {data.title}
            </Text>
            <Text
              numberOfLines={2}
              style={[
                CommonStyles.primaryText,
                {
                  marginTop: SizeUtils.translateDesignHeightToCode(10),
                  lineHeight: SizeUtils.translateDesignHeightToCode(25),
                  color: 'gray',
                  fontSize: SizeUtils.translateFontSizeToCode(20)
                }
              ]}
            >
              {data.desc}
            </Text>
          </View>
        </View>
        {this._BottomView(data)}
      </TouchableOpacity>
    )
  }
  _BottomView = data => (
    <View
      style={{
        flexDirection: 'row',
        paddingLeft: SizeUtils.translateDesignWidthToCode(10),
        marginBottom: SizeUtils.translateDesignHeightToCode(14),
        alignItems: 'center'
      }}
    >
      <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
        <TImage source={require('../../../resource/images/activity/persion.png')} style={{ width: 20, height: 20 }} />
        <Text style={[CommonStyles.secondaryText, { fontSize: SizeUtils.translateFontSizeToCode(24) }]}>
          {' ' + data.favoriters_num}
        </Text>
        <TImage
          source={require('../../../resource/images/home/jianyi.png')}
          style={{ marginLeft: 10, width: 25, height: 25 }}
        />
        <Text style={[CommonStyles.secondaryText, { fontSize: SizeUtils.translateFontSizeToCode(24) }]}>
          {' ' + data.post_comment_num}
        </Text>
      </View>
      {this._renderContentItemTagPer(data.is_favorited === 1 ? true : false, data)}
    </View>
  )
  //标签
  _renderContentItemTagPer(isjoin, data) {
    return (
      <View
        style={{
          marginLeft: SizeUtils.translateDesignWidthToCode(20),
          backgroundColor: '#fff',
          borderRadius: SizeUtils.translateDesignNumToCode(30),
          height: SizeUtils.translateDesignHeightToCode(30),
          borderColor: isjoin ? '#1ac60c' : '#ee3535',
          borderWidth: 0.5,
          marginRight: SizeUtils.translateDesignWidthToCode(10),
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center'
        }}
      >
        <TouchableOpacity onPress={this._shoucangQuanzi.bind(this, data)}>
          <Text
            style={{
              color: isjoin ? '#1ac60c' : '#ee3535',
              fontSize: SizeUtils.translateFontSizeToCode(22),
              textAlign: 'center',
              marginLeft: SizeUtils.translateDesignWidthToCode(10),
              marginRight: SizeUtils.translateDesignWidthToCode(10)
            }}
          >
            {isjoin ? '已加入' : '加入'}
          </Text>
        </TouchableOpacity>
      </View>
    )
  }
  _shoucangQuanzi(data) {
    new CommonCheckUserTypeAction().call(
      this,
      { needLogin: true, needVerify: true },
      this._onCheckIsUserCallback.bind(this, data)
    )
  }

  _onCheckIsUserCallback(data, result) {
    if (result) {
      let msg = data.is_favorited === 1 ? '是否确定退出圈子？' : '是否确定加入圈子？'
      Alert.alert('提示', msg, [
        {
          text: '确定',
          onPress: () => {
            new QuanziSendShoucangQuanziAction().call(this, { tdata: data, board_id: data.board_id })
          }
        },
        { text: '取消', onPress: () => {} }
      ])
    }
  }
  _getImageSource(data) {
    if (data.image_url) {
      return { uri: data.image_url }
    } else if (data.image_urls && data.image_urls && data.image_urls.length > 0) {
      return { uri: data.image_urls[0] }
    } else {
      return { uri: '' }
    }
  }
  _getQuanziImageSource(data) {
    if (data.avatar_url) {
      return { uri: data.avatar_url }
    } else {
      return { uri: '' }
    }
  }
  _onPressItem(data) {
    this.gotoPage(Config.pages.quanzi_content, data)
  }
  _renderTitleView() {
    return (
      <View
        style={{
          flexDirection: 'row',
          height: SizeUtils.translateDesignHeightToCode(Platform.OS === 'ios' ? 130 : 66),
          width: SizeUtils.getWindowSize().width,
          paddingTop: Config.tabBarTop,
          justifyContent: 'space-between',
          borderBottomWidth: this.props.pageData.showBottomBorder == false ? 0 : SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee',
          backgroundColor: '#ee3535'
        }}
      >
        <TouchableOpacity
          onPress={() => {
            this.goBack()
          }}
          disabled={!this.props.pageData.showLeftButton}
          style={{
            width: SizeUtils.translateDesignWidthToCode(200),
            paddingLeft: SizeUtils.translateDesignWidthToCode(40)
          }}
        >
          <View
            style={{
              flexDirection: 'row',
              height: SizeUtils.translateDesignHeightToCode(51),
              alignItems: 'center'
            }}
          >
            <Image
              source={require('../../../resource/images/common/Back-icon2.png')}
              style={{
                width: SizeUtils.translateDesignWidthToCode(24),
                height: SizeUtils.translateDesignWidthToCode(41)
              }}
            />
            <View
              style={{
                width: SizeUtils.translateDesignWidthToCode(200 - 40 - 24),
                paddingLeft: SizeUtils.translateDesignWidthToCode(5)
              }}
            />
          </View>
        </TouchableOpacity>
        <View style={{ height: SizeUtils.translateDesignNumToCode(30), marginTop: 0 }}>
          <Text
            style={{
              textAlign: 'center',
              fontSize: SizeUtils.translateFontSizeToCode(36),
              color: '#fff',
              fontFamily: 'STHeitiSC-Medium'
            }}
          >
            {' '}
            {'找圈'}{' '}
          </Text>
        </View>
        <View
          style={{
            width: SizeUtils.translateDesignWidthToCode(200),
            paddingRight: SizeUtils.translateDesignWidthToCode(40),
            alignItems: 'flex-end'
          }}
        >
          {this._renderNavigationBarRightButtonContent()}
        </View>
      </View>
    )
  }
  _renderNavigationBarRightButtonContent() {
    return (
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <TouchableOpacity
          onPress={() => {
            this.gotoPage(Config.pages.home_search)
          }}
        >
          <TImage
            source={require('../../../resource/images/workhard/search2.png')}
            style={{ width: 34, height: 34, marginRight: 15 }}
          />
        </TouchableOpacity>
        <NoticeIcon isWhite={true} authorization={this.props.authorization} />
      </View>
    )
  }
  _showPopover(ref) {
    this._popoverbtn.measure((ox, oy, width, height, px, py) => {
      this.props.showMoreRightBtn &&
        this.props.showMoreRightBtn({ x: px - 20, y: Platform.OS !== 'ios' ? py - 5 : py - 30, width: 0, height: 45 })
    })
  }
  _renderHeader(title, key) {
    return (
      <View
        style={{
          flexDirection: 'row',
          paddingLeft: SizeUtils.translateDesignWidthToCode(30),
          paddingRight: SizeUtils.translateDesignWidthToCode(20),
          backgroundColor: '#fff',
          width: SizeUtils.getWindowSize().width,
          paddingBottom: SizeUtils.translateDesignHeightToCode(22),
          justifyContent: 'space-between',
          paddingTop: SizeUtils.translateDesignHeightToCode(22),
          alignItems: 'center',
          borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee'
        }}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
          <TImage source={require('../../../resource/images/home/biaotitle.png')} style={{ width: 8, height: 30 }} />
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: '#333333',
              marginLeft: SizeUtils.translateDesignWidthToCode(8),
              borderWidth: 0,
              backgroundColor: '#00000000',
              fontWeight: 'bold'
            }}
          >
            {title}
          </Text>
        </View>
        {
          <TouchableOpacity
            onPress={() => {
              this._onPressMore(key)
            }}
          >
            <Text style={{ fontSize: SizeUtils.translateFontSizeToCode(28), color: '#999999' }}>{'更多 >'}</Text>
          </TouchableOpacity>
        }
      </View>
    )
  }
  _onPressMore(key) {
    if (key === 'my') {
      this.gotoPage(Config.pages.quanzi_findmine, { title: '我的圈子', isMy: true })
    } else if (key === 'hot') {
      this.gotoPage(Config.pages.quanzi_findlist, { title: '热门圈子', type: 'hot' })
    }
  }
}

const styles = StyleSheet.create({})

export default QuanziFindPage
